package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.swing.JOptionPane;

import model.Drink;



public class DrinkDAO {
	Connection conn = null;
	ResultSet rs = null;
	PreparedStatement pst = null;

	//constructor
	public DrinkDAO() {
		conn = DatabaseConnect.ConnectDb();
	}
	
	public Drink getDrink(int drinkId){
		// Open Connection; Convert row to domain object; return drink object; return new drink
		rs = null;
		Drink result = null;
		String sql = "select * from Drinks where DrinkID=?";
		try {
			pst = conn.prepareStatement(sql);
			pst.setInt(1, drinkId);

			rs = pst.executeQuery();

			if (rs.next()) {
				result = new Drink(rs.getString("DrinkName"), rs.getInt("DrinkID"),
						rs.getString("DrinkDesc"), rs.getDouble("drinkPrice"));
				}
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, "DrinkDao fault!!");
			return result;
		}
		return result;
	}
	
	public ArrayList<Drink> getDrinks() {
		// Open Connection

		// GET User rows
		// convert rows to domain objects
		// Return users object list
		return null;
	}
	
	public ResultSet getDrinkResultSet() {
		rs = null;
		String sql = "select * from Drinks";
		try {
			pst = conn.prepareStatement(sql);
			rs = pst.executeQuery();
			return rs;
		} catch (SQLException ex) {
			JOptionPane.showMessageDialog(null, "DrinkDao empty resultset");
		}
		return rs;
	}

	public void deleteDrink(String dId) {
		String sql = "delete from Drinks where DrinkID=?";
		try {
			pst = conn.prepareStatement(sql);
			pst.setInt(1, Integer.parseInt(dId));
			pst.executeUpdate();
			pst.close();
		} catch (Exception e) {
			System.out.println("DrinkDao, deleteDrink exception!");
		}
		
	}

	public void updateDrink(String dId, String name, String desc, String price) {
		String sql = "Update Drinks set DrinkName=?, DrinkDesc=? , " +
				"DrinkPrice=? Where DrinkID=?" ;
		try {
			pst = conn.prepareStatement(sql);
			pst.setString(1, name); pst.setString(2, desc);
			pst.setDouble(3, Double.parseDouble(price)); pst.setInt(4, Integer.parseInt(dId));
			
			pst.executeUpdate();
			pst.close();
		} catch (Exception e) {
			System.out.println("DrinkDao, UpdateDrink exception!");
		}
		
	}

	public void newDrink(String dId, String name, String desc, String price) {
		String sql = "insert into Drinks (DrinkID, DrinkName, DrinkDesc, DrinkPrice) values (?,?,?,?)";
		try {
			pst = conn.prepareStatement(sql);
			pst.setInt(1, Integer.parseInt(dId)); pst.setString(2, name); 
			pst.setString(3, desc); pst.setDouble(4, Double.parseDouble(price)); 
			
			pst.executeUpdate();
			pst.close();
		} catch (Exception e) {
			System.out.println("DrinkDao,NewDrink exception!");
		}
		
	}
	
	
}
